package com.my.hotel.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.my.hotel.entity.User;
import com.my.hotel.service.ClientService;
import com.my.hotel.service.RoleService;
import com.my.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/client")
public class ClientController {

    @Autowired
    private ClientService clientService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/getClientList")
    public String getClientList(Integer pageNo, Model model){
        if (null==pageNo){
            pageNo=1;
        }
        PageHelper.startPage(pageNo,5);
        String role_name="客户";
        List<User> clientList = clientService.getClientList(role_name);
        PageInfo<User> pageInfo = new PageInfo<User>(clientList);
        model.addAttribute("page",pageInfo);
        return "clientPage";
    }

    @RequestMapping("/toAddClientJsp")
    public String toAddClientJsp(){
        return "clientAdd";
    }

    @RequestMapping("/clientAdd")
    public String clientAdd(User user, HttpSession session,Model model){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date);
        user.setCreateTime(format);
        User userInfo = (User) session.getAttribute("userinfo");
        user.setOpratorId(userInfo.getId());
        userService.addUser(user);
        int maxId = userService.getMaxId();
        roleService.roleAdd(maxId);
        return "redirect:/client/getClientList";
    }

    @RequestMapping("/preUpdateClient")
    public String preUpdateClient(int id,Model model){
        User user = userService.getUserById(id);
        model.addAttribute("user",user);
        return "clientUpdate";
    }

    @RequestMapping("/updateClient")
    public String updateClient(User user,HttpSession session){
        String encode = new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(encode);
        User userinfo = (User) session.getAttribute("userinfo");
        user.setOpratorId(userinfo.getId());
        userService.updateUser(user);
        return "redirect:/client/getClientList";
    }

    @RequestMapping("/deleteClient")
    public String deleteClient(int id){
        userService.delUser(id);
        return "redirect:/client/getClientList";
    }
}
